$(function () {
  //右下角点击事件.登录\注册
  $('#login-reg').on('click', function () {
    $('.logoin-reg').show();
    $('.logoin-box').hide();
  });
  $('#login-box').on('click', function () {
    $('.logoin-reg').hide();
    $('.logoin-box').show();
  });
  //页面刷新获取本地存储的账号密码
  grtsecret();
  function grtsecret() {
    //获取名字并设置到
    $('#logoin-cdd').val(localStorage.getItem('loginName'));
    //获取密码
    $('#logoin-pwd').val(localStorage.getItem('loginPwd'));
  }
  // layui的正则匹配
  var form = layui.form;
  var layer = layui.layer;
  form.verify({
    pwd: [
      /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{6,18}$/,
      '密码必须6至12位且不能有空格且最少一个字母+数字',
    ],
    repwd: function (value) {
      var pwd = $('.logoin-reg [name=password]').val();
      if (value !== pwd) return '两次密码输入不一致';
    },
  });
  // 注册表单事件开始
  $('#form-reg').on('submit', function (e) {
    e.preventDefault();
    $.post(
      '/api/reguser',
      {
        username: $('#form-reg [name = username]').val(),
        password: $('#form-reg [name = password]').val(),
      },
      function (res) {
        console.log(res);
        if (res.status !== 0) {
          return layer.msg(res.message);
        }

        layer.msg(res.message + '跳转登陆页面');
        $('#login-box').click();
        $('#logoin-cdd').val($('#form-reg [name = username]').val());
        $('#logoin-pwd').val($('#form-reg [name = password]').val());
      }
    );
  });
  //登录表单事件开始
  $('#form-logoin').submit(function (e) {
    e.preventDefault();
    $.ajax({
      method: 'POST',
      url: '/api/login',
      data: $(this).serialize(),
      success: function (res) {
        if (res.status !== 0) return layer.msg(res.message);
        layer.msg(res.message);
        //将token的值储存到本地存储
        localStorage.setItem('token', res.token);
        //将login页面的账号密码存储到本地存储中
        var name = $('#logoin-cdd').val();
        var pwd = $('#logoin-pwd').val();
        localStorage.setItem('loginName', name);
        localStorage.setItem('loginPwd', pwd);
        //登陆成功跳转主页
        location.href = '/index.html';
      },
    });
  });
});
